package com.kakaxi.mybilibili.module.home.live.presenter;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.kakaxi.mybilibili.module.home.live.model.ILiveRoomMedalRankModel;
import com.kakaxi.mybilibili.module.home.live.model.LiveRoomMedalRankModel;
import com.kakaxi.mybilibili.module.home.live.view.ILiveRoomMedalRankView;
import com.kakaxi.mybilibili.bean.LiveRoomMedalRankItemBean;
import com.kakaxi.mybilibili.common.WebParamConst;
import com.vincestyling.netroid.Listener;
import com.vincestyling.netroid.NetroidError;

import java.util.List;

/**
 * 直播间粉丝榜控制层实现类
 * Created by kakaxi on 16/11/9.
 */

public class LiveRoomMedalRankPresenter implements ILiveRoomMedalRankPresenter {

    /** 视图层 **/
    private ILiveRoomMedalRankView mLiveRoomMedalRankView;

    /** 数据层 **/
    private ILiveRoomMedalRankModel mLiveRoomMedalRankModel;

    public LiveRoomMedalRankPresenter(ILiveRoomMedalRankView liveRoomMedalRankView) {
        mLiveRoomMedalRankView = liveRoomMedalRankView;
        mLiveRoomMedalRankModel = new LiveRoomMedalRankModel();
    }

    @Override
    public void initMedalRankData(int roomId) {
        mLiveRoomMedalRankView.showLoading();
        getMedalRankData(roomId);
    }

    @Override
    public void refreshMedalRankData(int roomId) {
        getMedalRankData(roomId);
    }

    /**
     * 获取礼物排行榜数据并处理
     *
     * @param roomId 直播间数据
     */
    private void getMedalRankData(int roomId) {
        mLiveRoomMedalRankModel.getMedalRankData(roomId, new Listener<JSONObject>() {
            @Override
            public void onSuccess(JSONObject response) {
                super.onSuccess(response);
                mLiveRoomMedalRankView.hideLoading();
                // 判断是否正确
                if (response.getString(WebParamConst.RESPONSE_CODE).equals
                        (WebParamConst.RESULT_CODE_OK)) {
                    // 获取数据,并把json转化为bean
                    String medalRankJsonArrStr = response.getJSONObject(WebParamConst
                            .RESPONSE_DATA).getJSONArray(WebParamConst
                            .RESPONSE_DATA_LIVE_ROOM_LIST).toString();
                    List<LiveRoomMedalRankItemBean> medalRankItemBeanList = JSON.parseArray
                            (medalRankJsonArrStr, LiveRoomMedalRankItemBean.class);
                    mLiveRoomMedalRankView.showGiftTopData(medalRankItemBeanList);
                } else {
                    mLiveRoomMedalRankView.showMessage(response.getString(WebParamConst
                            .RESPONSE_MESSAGE));
                }
            }

            @Override
            public void onError(NetroidError error) {
                super.onError(error);
                mLiveRoomMedalRankView.hideLoading();
            }
        });
    }

}
